package com.seed.uaa;

import cn.hutool.core.util.StrUtil;
import com.seed.core.action.Action;
import com.seed.core.pojo.seed.Seed;
import com.seed.util.ToSeedKit;
import com.seed.uaa.web.UaaController;
import com.seed.uaa.web.organization.OrganizationController;
import com.seed.uaa.web.role.RoleController;
import com.seed.uaa.web.user.UserController;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Uaa {
    private static Map<String, Seed> seeds;
    private static Map<String, Action> actions;

    public static Map<String, Seed> getSeeds() {
        if(seeds == null) {
            List<Class<?>> controllerList = new ArrayList<>();
            controllerList.add(UserController.class);
            controllerList.add(OrganizationController.class);
            controllerList.add(RoleController.class);

//            Boolean tenant = SeedSelector.configuration.getTenant();
//            if(tenant) {
//                controllerList.add(TenantController.class);
//            }
            seeds = ToSeedKit.toSeeds(controllerList);
        }

        return seeds;
    }

    public static Map<String, Action> getActions() {
        if(actions == null) {
            actions = ToSeedKit.toActions(UaaController.class);
        }
        return actions;
    }

    public static Action getAction(String seedName, RequestMethod method, String actionName) {
        if(StrUtil.isBlank(seedName)) return getAction(method, actionName);

        Seed seed = seeds.get(seedName);
        if(seed == null) return null;

        Map<String, Action> actions = seed.getActions();
        if(actions == null) return null;

        Action action = actions.get(actionName);
        if(action == null || action.getMethods() == null) return null;

        return action.getMethods().contains(method) ? action : null;
    }

    public static Action getAction(RequestMethod method, String actionName) {
        if(actions == null) return null;

        Action action = actions.get(actionName);
        if(action == null || action.getMethods() == null) return null;

        return action.getMethods().contains(method) ? action : null;
    }
}
